import 'dart:convert';
import 'package:f_enjoy_plus/utils/http.dart';
import 'package:f_enjoy_plus/utils/loading.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:dio/dio.dart' as dio;

class AddOrEditVM extends GetxController {
  static AddOrEditVM get to => Get.find(); // 添加这一行

  var houseList = [].obs;
  var selectedHouse = {}.obs;
  var repairTypeList = [].obs;
  var selectedRepairType = {}.obs;
  var mobile = ''.obs;
  var description = ''.obs;
  var appointment = ''.obs;
  var attachment = [].obs;

  final TextEditingController mobileController = TextEditingController();
  final TextEditingController descriptionController = TextEditingController();

  onSelectHouse(Map<String, dynamic> house) {
    selectedHouse.value = house;
  }

  onSelectRepairType(Map<String, dynamic> repairType) {
    selectedRepairType.value = repairType;
  }

  /// 获取房屋列表
  Future<void> fetchHouseList() async {
    try {
      final response = await http.get('/house');
      print('response: $response');
      houseList.value = response;
    } catch (e) {
      print('error: $e');
    }
  }

  /// 获取报修项目列表
  Future<void> fetchRepairTypeList() async {
    try {
      final response = await http.get('/repairItem');
      print('response: $response');
      repairTypeList.value = response;
    } catch (e) {
      print('error: $e');
    }
  }

  uploadImage(String path, int index) async {
    // 显示全局loading
    LoadingUtils.show(message: '上传中...');

    try {
      // 由于FormData和MultipartFile有命名冲突，需要指定前缀
      dio.FormData fd = dio.FormData.fromMap({
        'file': dio.MultipartFile.fromFileSync(
          path,
          filename: 'attachment${index}.jpg',
        ),
      });
      final res = await http.post('/upload', fd);
      print('res: $res');
      // 假设res是Map<String, dynamic>
      attachment.add(res);
      print('attachment.value： ${attachment}');
    } catch (e) {
      print(e);
    } finally {
      // 隐藏全局loading
      LoadingUtils.hide();
    }
  }

  Future<void> submit() async {
    try {
      final repairRequest = RepairRequest(
        houseId: selectedHouse['id'],
        repairItemId: selectedRepairType['id'],
        mobile: mobileController.text,
        appointment: appointment.value,
        description: description.value,
        attachment:
            attachment
                .map((e) => Attachment(id: e['id'], url: e['url']))
                .toList(),
      );
      print('repairRequest: $repairRequest');
      final response = await http.post('/repair', repairRequest.toJson());
      print('response: $response');
    } catch (e, stack) {
      print('请求异常: $e');
      print('堆栈: $stack');
    }
  }

  @override
  void onInit() {
    super.onInit();
    fetchHouseList();
    fetchRepairTypeList();
  }

  @override
  void onClose() {
    mobileController.dispose();
    descriptionController.dispose();
    super.onClose();
  }
}

class UploadImageResponse {
  final String id;
  final String url;

  UploadImageResponse({required this.id, required this.url});

  @override
  String toString() {
    return 'UploadImageResponse{id: $id, url: $url}';
  }
}

///empty object
class RepairRequest {
  ///预约日期
  String appointment;

  ///附件信息，0-9个
  List<Attachment> attachment;

  ///问题描述-做多200字
  String description;

  ///已审核通过的房屋id
  String houseId;

  ///主键id,保存时，必有
  String? id;

  ///手机号
  String mobile;

  ///维修项目code
  String repairItemId;

  RepairRequest({
    required this.appointment,
    required this.attachment,
    required this.description,
    required this.houseId,
    this.id,
    required this.mobile,
    required this.repairItemId,
  });

  Map<String, dynamic> toJson() {
    return {
      'appointment': appointment,
      'attachment': attachment.map((e) => e.toJson()).toList(),
      'description': description,
      'houseId': houseId,
      if (id != null) 'id': id, // id 可选
      'mobile': mobile,
      'repairItemId': repairItemId,
    };
  }
}

class Attachment {
  ///附件id
  String id;

  ///附件url
  String url;

  Attachment({required this.id, required this.url});

  factory Attachment.fromJson(Map<String, dynamic> json) {
    return Attachment(id: json['id'], url: json['url']);
  }

  Map<String, dynamic> toJson() {
    return {'id': id, 'url': url};
  }
}
